package org.example.service.impl;

import cn.hutool.core.bean.BeanException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.GoodsMapper;
import org.example.mapper.InventoryMapper;
import org.example.pojo.*;
import org.example.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private InventoryMapper inventoryMapper;

    /**
     * 分页查询商品信息
     */
    @Override
    public PageBean<Goods> list(Integer page, Integer pageSize, Integer categoryId, String goodsName,Integer vendorId) {
        PageHelper.startPage(page, pageSize);
        Page<Goods> pageInfo = goodsMapper.list(categoryId, goodsName, vendorId);
        return new PageBean<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    /**
     * 添加商品
     * @param goods
     */
    @Override
    @Transactional
    public void add(Goods goods) {
        Goods goods1 = goodsMapper.getByName(goods);
        if (goods1 != null){
            throw new RuntimeException("商品名不能重复");
        }
        goodsMapper.add(goods);
        // 新注册的商品插入到库存表中
        Inventory inventory = Inventory.builder()
                .goods_id(goods.getId())
                .location("未指定")
                .last_updated(LocalDateTime.now())
                .build();
        inventoryMapper.add(inventory);
    }

    /**
     * 修改商品
     * @param goods
     */
    @Override
    public void update(Goods goods) {
       goods.setUpdateTime(LocalDateTime.now());
       goodsMapper.update(goods);
    }

    /**
     * 删除商品
     * @param id
     */
    @Override
    @Transactional
    public void delete(Integer id) {
        // 删除商品之前要查看库存信息，如果有库存，则不能删除，如果没有库存这同时删除库存表
        Integer quantity = inventoryMapper.getByGoodsId(id);
        System.out.println(quantity);
        if (quantity > 0){
            throw new RuntimeException("该商品有库存，不能删除");
        }
        inventoryMapper.delete(id);
        goodsMapper.delete(id);
    }

    /**
     * 分页查询库存小于10的列表
     */
    @Override
    public PageBean<Goods> list2(Integer pageNum, Integer pageSize, Integer categoryId, String goodsName, Integer vendorId) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Goods> pageInfo = goodsMapper.list2(categoryId, goodsName, vendorId, 10);
        pageInfo.getResult().forEach(item -> {
            // 库存10到1的给个remark提示信息，为0了给更多警告
            if (item.getQuantity() < 10){
                item.setRemark("库存不足10，请及时补货");
            }
            if (item.getQuantity() == 0){
                item.setRemark("库存为0，请赶快处理，不然影响营业了！！！");
            }
        });
        return new PageBean<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    /**
     * 临期或过期商品列表
     */
    @Override
    public List<GoodsOverdueVO> list3() {
        // 查询所有商品
        List<Goods> result = goodsMapper.list3();
        log.info("查询所有商品：{}", result);
        // 放置临期或过期商品，并给Goods类添加提示信息
        List<GoodsOverdueVO> list = new ArrayList<>();
        for (Goods goods : result) {
            LocalDate overdueDate = goods.getOverdueDate();
            if (overdueDate.isBefore(LocalDate.now())) {
                GoodsOverdueVO goodsOverdueVO = GoodsOverdueVO.builder()
                        .goodsName(goods.getGoodsName())
                        .produceDate(goods.getProduceDate())
                        .overdueDate(goods.getOverdueDate())
                        .message("已过期，请及时处理！！！")
                        .build();
                list.add(goodsOverdueVO);
            }else if ( overdueDate.isBefore(LocalDate.now().plusDays(10))){
                GoodsOverdueVO goodsOverdueVO = GoodsOverdueVO.builder()
                        .goodsName(goods.getGoodsName())
                        .produceDate(goods.getProduceDate())
                        .overdueDate(goods.getOverdueDate())
                        .message("保质期不足10天，请及时清仓！！！")
                        .build();
                list.add(goodsOverdueVO);
            }
        }
         return list;
    }

    /**
     * 批量删除商品
     * @param ids
     */
    @Override
    public void batchDelete(List<Integer> ids) {
        for (Integer id : ids){
            goodsMapper.delete(id);
        }
    }

    /**
     * 临期或过期商品列表
     */
    @Override
    public PageBean<ExpireGoodsVo> expireList(Integer pageNum, Integer pageSize, String goodsName, Integer category) {
        PageHelper.startPage(pageNum, pageSize);
        Page<ExpireGoodsVo> pageInfo = goodsMapper.expireList(goodsName, category);
        pageInfo.getResult().forEach(item -> {
            if (item.getOverdueDate().isBefore(LocalDate.now())){
                item.setMessage("已过期，请及时处理！！！");
            }else if ( item.getOverdueDate().isBefore(LocalDate.now().plusDays(10))){
                item.setMessage("保质期不足10天，请及时清仓！！！");
            }else {
                item.setMessage("好日期商品，无需担心");
            }
            // 计算overdueDate和当天的天数差
            long daysLeft = item.getOverdueDate().toEpochDay() - LocalDate.now().toEpochDay();
            item.setDaysLeft((int) daysLeft);
        });
        return new PageBean<>(pageInfo.getTotal(), pageInfo.getResult());
    }


    /**
     * 获取所有商品
     * @return
     */
    @Override
    public List<Goods> getAllGoods() {
        return goodsMapper.getGoodsList();
    }
}
